import os
import json
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QFileDialog, QMessageBox)

from modules.gui.account_table import AccountTableWidget
from modules.gui.dialogs import ImportDialog
from modules.utils.register_utils import OUTLOOK_ACCOUNTS_JSON, load_outlook_accounts, load_registered_accounts

class AccountsTab(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.registered_accounts = {}  # 存储已注册账号
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # Account table
        self.account_table = AccountTableWidget()
        layout.addWidget(self.account_table)
        
        # Table control buttons
        button_layout = QHBoxLayout()
        
        add_button = QPushButton("添加行")
        add_button.clicked.connect(self.account_table.add_empty_row)
        button_layout.addWidget(add_button)
        
        remove_button = QPushButton("删除选中")
        remove_button.clicked.connect(self.account_table.remove_selected_rows)
        button_layout.addWidget(remove_button)
        
        import_button = QPushButton("导入账号")
        import_button.clicked.connect(self.import_accounts)
        button_layout.addWidget(import_button)
        
        save_button = QPushButton("保存账号")
        save_button.clicked.connect(self.save_accounts)
        button_layout.addWidget(save_button)
        
        layout.addLayout(button_layout)
        
        # Load existing accounts
        self.load_existing_accounts()
    
    def load_existing_accounts(self):
        """加载现有账号并检查哪些已注册"""
        # 首先加载已注册账号
        self.registered_accounts = load_registered_accounts()
        
        # 然后加载Outlook账号
        accounts = load_outlook_accounts()
        
        # 标记已注册的账号
        for account in accounts:
            email = account.get("email", "")
            if email in self.registered_accounts:
                # 如果账号已注册且有token和密码
                if self.registered_accounts[email].get("token") and self.registered_accounts[email].get("cursor_password"):
                    account["registered"] = True
                    account["cursor_password"] = self.registered_accounts[email].get("cursor_password")
                    account["token"] = self.registered_accounts[email].get("token")
        
        # 显示账号
        self.account_table.load_accounts(accounts)
        
    def save_accounts(self):
        accounts = self.account_table.get_accounts()
        if not accounts:
            QMessageBox.warning(self, "警告", "没有账号可保存")
            return False
            
        try:
            data = {"accounts": accounts}
            with open(OUTLOOK_ACCOUNTS_JSON, 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存账号失败: {str(e)}")
            return False
    
    def import_accounts(self):
        # 显示导入对话框
        dialog = ImportDialog(self)
        if dialog.exec_() == ImportDialog.Accepted:
            self.import_accounts_txt()
    
    def import_accounts_txt(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择TXT文件", "", "文本文件 (*.txt)"
        )
        
        if not file_path:
            return
            
        try:
            accounts = []
            invalid_lines = []
            
            with open(file_path, 'r', encoding='utf-8') as file:
                for line_num, line in enumerate(file, 1):
                    line = line.strip()
                    if not line:  # 跳过空行
                        continue
                    
                    # 使用逗号分隔符拆分
                    parts = line.split(',')
                    
                    if len(parts) >= 2:
                        # 获取邮箱（第一部分）和密码（第二部分）
                        email = parts[0].strip()
                        password = parts[1].strip()
                        
                        if email and password:
                            account = {"email": email, "password": password}
                            
                            # 检查账号是否已注册
                            if email in self.registered_accounts:
                                if self.registered_accounts[email].get("token") and self.registered_accounts[email].get("cursor_password"):
                                    account["registered"] = True
                                    account["cursor_password"] = self.registered_accounts[email].get("cursor_password")
                                    account["token"] = self.registered_accounts[email].get("token")
                                    
                            accounts.append(account)
                        else:
                            invalid_lines.append(line_num)
                    else:
                        invalid_lines.append(line_num)
            
            if accounts:
                self.account_table.load_accounts(accounts)
                
                if invalid_lines:
                    QMessageBox.warning(
                        self, 
                        "警告", 
                        f"第 {', '.join(map(str, invalid_lines))} 行格式不正确，已忽略"
                    )
            else:
                raise ValueError("未找到有效账号，请确保每行格式为：账号,密码")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导入TXT账号失败: {str(e)}")
            
    def get_accounts(self):
        """获取未注册的账号"""
        all_accounts = self.account_table.get_accounts()
        
        # 过滤掉已注册的账号
        accounts_to_register = []
        for account in all_accounts:
            email = account.get("email", "")
            if not (email in self.registered_accounts and 
                    self.registered_accounts[email].get("token") and 
                    self.registered_accounts[email].get("cursor_password")):
                accounts_to_register.append({
                    "email": email,
                    "password": account.get("password", "")
                })
        
        return accounts_to_register 